#include "Button.h"
#include "base/Utility.h"
#include "base/UITheme.h"
#define SetAttr(AttrName) SetAttribute(AttrName, ele->Attribute(AttrName));
void Button::ParseXmlElement(TiXmlElement* ele)
{
      SetAttr("pos")
      SetAttr("size")
      SetAttr("name")
}

Control* Button::CreateControl(std::string sControlClassName)
{
    Control* ctrl = dynamic_cast<Control*>(BlueprintScriptLibrary::BlueprintDataPool::GetInstance()->createInstFuncs[sControlClassName]());
    ctrl->rootWindow = rootWindow;
    return ctrl;
}
bool Button::SetAttribute(const char* attrName, const char* attrVal)
{
    if (attrVal == nullptr) return false;
    if (strcmp(attrName, "pos") == 0)
    {
        int x, y;
        sscanf_s(attrVal, "%d,%d", &x, &y);
        pos.x = x;
        pos.y = y;
        return true;
    }
    else   if (strcmp(attrName, "name") == 0)
    {
        name = attrVal;
        return true;
    }
    else   if (strcmp(attrName, "size") == 0)
    {
        int x, y;
        sscanf_s(attrVal, "%d,%d", &x, &y);
        size.x = x;
        size.y = y;
        return true;
    }
    else   if (strcmp(attrName, "content") == 0)
    {
        content.val = attrVal;
        return true;
    }
  
    return true;
}
void Button::OnDraw()
{
    DrawBorder();
    ButtonState state = isMouseDown ? ButtonState::Normal : ButtonState::Pressed;
    UITheme::GetInst().DrawButtonBK(state, pos.x.val, pos.y.val, size.x.val, size.y.val,zIndex.val);
    std::wstring wstr = Utility::Utf82Unicode(content.val);
    TrueTypeFont* ttf = TrueTypeFont::GetInst();
    ttf->drawText(const_cast<wchar_t*>(wstr.data()), pos.x.val, pos.y.val + size.y.val - 20,zIndex.val+1, size.x.val, size.y.val);
}
void Button::onMouseButtonDown(int button, int x, int y)
{
    isMouseDown = true;
   // printf("button down:%s\r\n",content.val.data());
  
}
BlueprintScriptLibrary::Class* Button::GetClass()
{
    return nullptr;
}
void Button::onMouseButtonUp(int button, int x, int y)
{
    onClick.Invoke(this, content);
    isMouseDown = false;
    MouseButtonEventArgs arg;
    arg.button = button;
    arg.x = x;
    arg.y = y;
    events.mouseUp.Invoke(this, arg);
}
void Button::onMouseMove(int x, int y)
{

}